package com.mingtu.jgspatrol.base;

import android.app.Activity;
import android.os.StrictMode;

import androidx.annotation.NonNull;
import androidx.room.Room;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.hm.lifecycle.api.ApplicationLifecycleManager;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.view.LoadingDialog;
import com.mingtu.jgspatrol.BuildConfig;
import com.mingtu.jgspatrol.activity.MainActivity;
import com.mingtu.jgspatrol.room.SignInEventDao;
import com.mingtu.jgspatrol.room.SignInEventDatabase;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.mob.MobSDK;
import com.mob.moblink.MobLink;
import com.mob.moblink.RestoreSceneListener;
import com.mob.moblink.Scene;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.auth.AuthProvider;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName :
 * @Author : wkk
 * @Date : 2021-5-6 09:36:07
 * @Email : 1281573890@qq.com
 * @Eescription :
 */
public class Application extends BaseApplication {
    private String TAG = "Qb";
    private static LoadingDialog downLoadDialog;
    private SignInEventDao signInEventDao;
    private static Application myApplication = null;

    @Override
    public void onCreate() {
        super.onCreate();
        myApplication = this;
        ApplicationLifecycleManager.init();
        ApplicationLifecycleManager.onCreate(this);

        //需要设置下 HOST   HOST2
        Constant.getInstance().setTileUrl("https://static.mingtukeji.com/jigongshan/geodata/dom/{z}/{x}/{y}.png");
        Constant.getInstance().setSERVER(MyConstant.SERVER); //测试用
        Constant.getInstance().setAREAUrl(MyConstant.GET_AREA);
        Constant.getInstance().setHOST("/jgs-api/app/api");
        Constant.getInstance().setHOST2("/jgs-api/app");
        Constant.getInstance().setHOST3("/jgs-api/air");
        Constant.getInstance().setHOST4("/jgs-api/app/camera");
        Constant.getInstance().setHOST11("/jgs-api/app/document");
        Constant.getInstance().setIS_OPEN_REAL_TIME_UPLOAD(true); //是否开启实时上传
        Constant.getInstance().setIS_SHOW_LOG(true); //是否开启log日志（打包的时候关闭）
        Constant.getInstance().setIsXUpdate(true); //是否开启XUpdate 更新
        Constant.getInstance().setLocationCityName("信阳市");
        Constant.getInstance().setShare(false);

        Constant.getInstance().setIS_PUBLISH(false);
        Constant.getInstance().setURL_AGREEMENT(MyConstant.URL_AGREEMENT);
        Constant.getInstance().setURL_PRIVACY(MyConstant.URL_PRIVACY);


        if (AppUtils.getAppVersionName().indexOf("beta") == -1) { //当版本号含有beta的时候，异常信息【不上传】到后台
            Thread.setDefaultUncaughtExceptionHandler(new OwnUncaughtExceptionHandler());//捕获全局异常
        }

        //ShareSDK
        MobSDK.init(this, "3b3a1d4556c18", "24fb7b6792c215377547cd1fafd7b1aa");
        MobLink.setRestoreSceneListener(new SceneListener());

        //友盟初始化
//        UMConfigure.init(this, "607e51b55844f15425de7deb", "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
//        // 微信设置
//        PlatformConfig.setWeixin("wx1d2b430bc28499dd", "c642e100d4aa2c1858e105b47f1d2a03");
//        PlatformConfig.setWXFileProvider(AppUtils.getAppPackageName() + ".fileprovider");


        //创建巡护相关数据的数据库
        SignInEventDatabase signInEventDatabase = Room.databaseBuilder(this, SignInEventDatabase.class, "sign_in_event_database")
                .allowMainThreadQueries()
                .fallbackToDestructiveMigration()
                .build();

        signInEventDao = signInEventDatabase.getSignInEventDao();
//        enabledStrictMode();
        SPStaticUtils.put(SPTools.CHANNEL_ID, "112267");

        initNIMClient();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();

        ApplicationLifecycleManager.onTerminate();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();

        ApplicationLifecycleManager.onLowMemory();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);

        ApplicationLifecycleManager.onTrimMemory(level);
    }

    /**
     * 初始化NIM SDK
     */
    private void initNIMClient(){
        SDKOptions sdkOptions = new SDKOptions();
        sdkOptions.appKey = BuildConfig.YX_APP_KEY;
        sdkOptions.authProvider = new AuthProvider() { //动态-token-登录
            @Override
            public String getToken(String account) {
                MyLogUtil.e("AuthProvider", "account== " + account);
                long curTime = TimeUtils.getNowMills();
                String appKey = BuildConfig.YX_APP_KEY;
                String appSecret = BuildConfig.YX_APP_SECRET;
                long ttl = 600;
                String data = appKey + account + curTime + ttl + appSecret;
                String signature = EncryptUtils.encryptSHA1ToString(data).toLowerCase();
                HashMap<String, Object> authMap = new HashMap<>();
                authMap.put("signature", signature);
                authMap.put("curTime", curTime);
                authMap.put("ttl", ttl);
                String jsonStr = GsonUtils.toJson(authMap);
                String token = EncodeUtils.base64Encode2String(jsonStr.getBytes());
                return token;
            }
        };
        NIMClient.init(this, null, sdkOptions);
    }
    private void enabledStrictMode() {
        //开启Thread策略模式
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectCustomSlowCalls() //API等级11，使用StrictMode.noteSlowCode ，监测自定义运行缓慢函数
                .detectDiskReads() // 检测在UI线程读磁盘操作
                .detectDiskWrites() // 检测在UI线程写磁盘操作
                .detectNetwork()//监测主线程使用网络
                .penaltyLog() //在Logcat 中打印违规异常信息
                .penaltyDialog()//监测到上述状况时弹出对话框
                .build());
        //开启VM策略模式
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects() ////监测sqlite泄露
                .setClassInstanceLimit(MainActivity.class, 1) //// 设置某个类的同时处于内存中的实例上限，可以协助检查内存泄露
                .detectLeakedClosableObjects() ////监测没有关闭IO对象
                .detectActivityLeaks()
                .penaltyLog()
                .build());

    }


    public class SceneListener extends Object implements RestoreSceneListener {

        @Override
        public Class<? extends Activity> willRestoreScene(Scene scene) {
            String path = scene.getPath();
//            HashMap<String, Object> hashMap = scene.getParams();
            Map<String, Class<? extends Activity>> pathMap = MyConstant.getInstance().PATH_MAP_LOCAL;
            if (pathMap.keySet().contains(path)) {
                return pathMap.get(path);
            }
            return null;
        }

        @Override
        public void notFoundScene(Scene scene) {
            Scene scene1 = scene;
            MyLogUtil.e("testtest", "notFoundScene===");
        }

        @Override
        public void completeRestore(Scene scene) {
            Scene scene1 = scene;
            MyLogUtil.e("testtest", "completeRestore===");
        }
    }

    public class OwnUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

        @Override
        public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
            StackTraceElement[] elements = e.getStackTrace();

            StringBuilder reason = new StringBuilder(e.toString());

            if (elements != null && elements.length > 0) {

                for (StackTraceElement element : elements) {

                    reason.append("\n");
                    reason.append(element.toString());
                }
            }

            String errorString = reason.toString();
            MyLogUtil.e("uncaughtException", "error==" + errorString);
            FileIOUtils.writeFileFromBytesByChannel(errorLogFilePath(), errorString.getBytes(), true);
            android.os.Process.killProcess(android.os.Process.myPid());

        }
    }

    public static String errorLogFilePath() {
        String errorLogPath = PathUtils.getCachePathExternalFirst() + "/" + "errorLog.txt";
        return errorLogPath;
    }

    public static void showMyDownLoadDialog() {
        try {
            if (downLoadDialog == null) {
                downLoadDialog = new LoadingDialog(ActivityUtils.getTopActivity(), "下载中...");
            }
            if (downLoadDialog.isShowing()) {
                downLoadDialog.dismiss();
            }
            downLoadDialog.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void hideMyDownLoadDialog() {

        try {
            if (downLoadDialog != null
                    && downLoadDialog.isShowing()) {
                downLoadDialog.dismiss();
            }
        } catch (Exception e) {
            downLoadDialog = null;
            e.printStackTrace();
        }

    }

    public SignInEventDao getSignInEventDao() {
        return signInEventDao;
    }

    public void setSignInEventDao(SignInEventDao signInEventDao) {
        this.signInEventDao = signInEventDao;
    }

    public static Application getApplication() {
        return myApplication;
    }
}
